package dingyunchi.job.dao.impl;

import dingyunchi.job.dao.CourseDao;
import dingyunchi.job.entity.Course;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CourseDaoImpl implements CourseDao {
    private final JdbcTemplate jdbcTemplate;

    public CourseDaoImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public Course save(Course course) {
        String sql = "INSERT INTO course (course_name, credit, teacher) VALUES (?,?,?)";
        jdbcTemplate.update(sql, course.getCourseName(), course.getCredit(), course.getTeacher());
        Long id = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Long.class);
        course.setId(id);
        return course;
    }

    @Override
    public Course findById(Long id) {
        String sql = "SELECT * FROM course WHERE id =?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Course.class), id);
    }

    @Override
    public List<Course> findAll() {
        String sql = "SELECT * FROM course";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Course.class));
    }

    @Override
    public void update(Course course) {
        String sql = "UPDATE course SET course_name =?, credit =?, teacher =? WHERE id =?";
        jdbcTemplate.update(sql, course.getCourseName(), course.getCredit(), course.getTeacher(), course.getId());
    }

    @Override
    public void delete(Long id) {
        String sql = "DELETE FROM course WHERE id =?";
        jdbcTemplate.update(sql, id);
    }
}